<template>
  <view class="commonlist">
    <view class="commonlist-header">
      <!-- <view class="filter-icon" @click="openFilter">
        筛选
        <u-icon name="arrow-down-fill" color="#333" size="28" />
      </view> -->
      <u-search
        v-model="search.searchWord"
        class="commonlist-search"
        :show-action="false"
        placeholder="搜索"
        clearable
        bg-color="#EDEDEE"
        shape="square"
        @change="startSearch"
      />
    </view>

    <view class="commonlist-container">
      <Hr-Pull-Load
        ref="hrPullLoad"
        :height="-1"
        :bottom-tips="bottomTips"
        @loadMore="loadMore"
        @refresh="refresh"
      >
        <Common-Lists
          :data-list="list"
          @itemClick="itemClick"
        />
      </Hr-Pull-Load>
    </view>

  </view>
</template>

<script type="text/ecmascript-6">
import CommonLists from 'pages/CommomList/components/CommonLists';

import _ from 'lodash';
import { createNamespacedHelpers } from 'vuex';
import { commonRequest } from '@/api/commonlist';
import { getAppId } from '@/utils/local';
import { getLocalStorage, setLocal, removeLocalStorage } from '@/utils/utils';

export const BUSINESSFIELDSKEY = 'BUSINESSFIELDSKEY';
const { mapMutations, mapState } = createNamespacedHelpers('formModule');

export default {
  components: {
    CommonLists
  },

  data() {
    return {
      search: {
        searchWord: '',
        pageSize: 20,
        pageIndex: 1,
        total: 0
      },

      list: [],

      routeQuery: {},

      bottomTips: ''
    };
  },

  computed: {
    ...mapState({
      stateDetailRenderList: state => state.listDetailRenderData,
      stateBusinessFields: state => state.businessFields
    })
  },

  mounted() {
    this.initData();
    this.startSearch = _.debounce(this.startSearch, 500);
  },

  methods: {
    ...mapMutations(
      [
        'setListDetailRenderData',
        'setBusinessFields'
      ]
    ),

    refresh() {
      this.clear();
      this.getListData().then(() => {
        this.$refs.hrPullLoad.reSet();
      });
    },

    // 搜索
    startSearch(v) {
      this.clear();
      this.getListData(v);
    },

    initData() {
      this.routeQuery = _.cloneDeep(this.$route.query);
      // commonRequest({}, 'aaa/bbb');
      this.getListData();
    },

    getListData(name) {
      const {
        search: {
          pageSize,
          pageIndex
        }
      } = this;
      const requestData = {
        pageSize,
        pageIndex,
        appId: getAppId(),
        userId: getLocalStorage('userId'),
        name
      };

      return commonRequest(requestData, '/modelForm/list').then(res => {
        if (res.success) {
          this.list = [...this.list, ...res.data];
          this.search.total = res.total;
        } else {
          this.clear();
        }
        return Promise.resolve(res);
      });
    },

    itemClick(item) {
      const {
        tableInfo,
        isApprove,
        businessFields,
        isBusinessData, // 1的时候展示业务字段
        id
      } = item;

      const children = tableInfo.children || [];
      const mb = children.find(item => item.tableName.includes('模板内容'));
      const tableIds1 = [mb && mb.id];
      const tableIds2 = children.reduce((p, c) => {
        if (!c.tableName.includes('模板内容')) {
          p.push(c.id);
        }
        return p;
      }, []);

      // ['模板内容id', '留着备用']
      const tableIds = [...tableIds1, ...tableIds2].join(',');
      const params = `?tableIds=${tableIds}&isApprove=${isApprove}&listId=${id}&${BUSINESSFIELDSKEY}=${isBusinessData}`;
      removeLocalStorage(BUSINESSFIELDSKEY);
      this.setBusinessFields([]);
      this.setListDetailRenderData([]);
      if (isBusinessData === 1) {
        this.setBusinessFields(businessFields);
        setLocal({
          [BUSINESSFIELDSKEY]: businessFields
        });
      }
      this.$router.push(`/listDetail` + params);
    },

    clear() {
      this.list = [];
      this.search.pageIndex = 1;
      this.search.total = 0;
    },

    // 上拉加载
    loadMore() {
      if (((this.search.pageIndex) * this.search.pageSize) >= this.search.total) {
        this.bottomTips = 'nomore';
      } else {
        this.bottomTips = 'loading';
        this.search.pageIndex++;
        this.getListData().then(() => {
          this.bottomTips = '';
        });
      }
    }
  }

};
</script>

<style lang="scss" scoped>
.commonlist {
  .commonlist-header {
    display: flex;
    background-color: #fff;

    .filter-icon {
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80px;
      padding: 0 16px;
    }
    .commonlist-search {
      padding: 8px 16px;
    }
  }

  .commonlist-container {
    width: 100%;
    height: calc(100vh - 48px);
    overflow: auto;
  }
}
</style>
